package com.hejun.securitywebsoceket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig  {
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Bean
    UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager= new InMemoryUserDetailsManager();
        UserDetails user1= User.withUsername("user1").password(passwordEncoder().encode("123")).roles("admin").build();
        UserDetails user2= User.withUsername("user2").password(passwordEncoder().encode("123")).roles("user").build();
        manager.createUser(user1);
        manager.createUser(user2);
        return manager;
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception {
        security.authorizeHttpRequests().anyRequest().authenticated();
        security.formLogin().permitAll();
        //会话管理配置,设置一个用户只能建立一个会话
        security.sessionManagement()
                .maximumSessions(1)
                .sessionRegistry(sessionRegistry());

        return security.build();

    }




    @Bean //此顶配置后面用来获取所有登录用户
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }



}